package com.yc.login.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bean.Result;
import com.yc.login.bean.LoginProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    LoginProperties properties;

    ObjectMapper objectMapper = new ObjectMapper();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object myinfo=session.getAttribute(properties.getSessionKey());
        if(myinfo==null){
            String accept = request.getHeader("Accept");
            if(accept.startsWith("application/json")){
                //如果是ajax请求，返回result，提示未登录
                Result result=new Result(0,"请登录系统",null);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            }else{
                //获取访问地址
                String requestURI = request.getRequestURI();
                String queryString = request.getQueryString();
                String path=requestURI;
                if(queryString!=null){
                    path=path+"?"+queryString;
                }
                session.setAttribute("goto",path);
                //如果是表单请求（xxx.html） 跳转到登录页面
                response.sendRedirect("/login/demo.html?cause=nologin");
            }
            return false;
        }
        return true;
    }
}
